#include "dlgexportlease.h"
#include "ui_dlgexportlease.h"
#include <QFileDialog>
#include <QDebug>


DlgExportLease::DlgExportLease(HousingDBMS *p_dbms, DlgSettings *p_settings, QWidget *parent) :
    QDialog(parent),
    mp_dbms(p_dbms),
    mp_settings(p_settings),
    ui(new Ui::DlgExportLease)
{
    ui->setupUi(this);
    connect(ui->btn_hide, SIGNAL(clicked()), this, SLOT(close()));
    connect(ui->btn_export_lease, SIGNAL(clicked()), this, SLOT(generate_lease()));
}

DlgExportLease::~DlgExportLease()
{
    delete ui;
}

void DlgExportLease::on_chb_show_word_clicked(bool checked)
{
    ui->chb_quit_word->setEnabled(checked);
    ui->chb_quit_word->setChecked(!checked);
}

int DlgExportLease::exec(const QHash<int, QVariant> &qh_lease)
{
    mqh_lease = qh_lease;
    ui->lease_info->setText(mp_dbms->get_lease_info(qh_lease));
    return QDialog::exec();
}

#ifdef Q_OS_WIN
    void DlgExportLease::replace(SleeWordDoc *p_doc, QString qstr_target, QString qstr_new)
    {
        bool b_res = true;
        while(b_res)
        {
            b_res = p_doc->replace(qstr_target, qstr_new);
        }

    }

#endif


void DlgExportLease::generate_lease()
{
    QStringList qstr_m_list;
    qstr_m_list<<RUSTR("января") \
               <<RUSTR("февраля") \
               <<RUSTR("марта") \
               <<RUSTR("апреля") \
               <<RUSTR("мая") \
               <<RUSTR("июня") \
               <<RUSTR("июля") \
               <<RUSTR("августа") \
               <<RUSTR("сентября") \
               <<RUSTR("октября") \
               <<RUSTR("ноября") \
               <<RUSTR("декабря");

    QString qstr_export_path = mp_settings->get_export_dirpath();
    QString qstr_filename = RUSTR("Договор №");
    qstr_filename += mqh_lease[FLD_LS_NUM].toString();
    qstr_filename += " ";
    qstr_filename += mp_dbms->get_tenant_fio(mqh_lease[FLD_LS_TINDEX]);
    qstr_filename += " ";
    qstr_filename += mp_dbms->get_apartment_addr(mqh_lease[FLD_LS_AINDEX]);
    qstr_filename += ".doc";
    qstr_filename.replace(' ', '_');

    QString qstr_filenamepath = qstr_export_path + "/" + qstr_filename;

    if(ui->chb_use_dlg->isChecked())
    {
        QFileDialog qdlg_save_file;
        qdlg_save_file.setDirectory(qstr_export_path);
        qdlg_save_file.selectFile(qstr_filename);
        qdlg_save_file.setFilter("*.doc");
        qdlg_save_file.setDefaultSuffix("doc");
        if(!qdlg_save_file.exec()) return;
        qstr_filenamepath = qdlg_save_file.selectedFiles().at(0);
    }
    lakhMsg()<<RUSTR("Файл договора:")<<qstr_filenamepath;

    QString qstr_template_file = mp_settings->get_doc_dirpath()+"/"+"lease.doc";
    if(!QFile::exists(qstr_template_file))
    {
        lakhMsgE()<<RUSTR("Ошибка. Не найден файл шаблона договора.")<<qstr_template_file;
        return;
    }
    qDebug()<<Q_FUNC_INFO<<" path used to save"<<qstr_filenamepath;
    qDebug()<<Q_FUNC_INFO<<" now copy template ...";
    if(QFile::exists(qstr_filenamepath))
    {
        QFile::remove(qstr_filenamepath);
    }
    if(!QFile::copy(qstr_template_file, qstr_filenamepath))
    {
        lakhMsgE()<<RUSTR("Ошибка. Невозможно создать файл договора. Проверте настройки. ")<<qstr_filenamepath;
        return;
    }

#ifdef  Q_OS_WIN
    qDebug()<<Q_FUNC_INFO<<" create Word object ...";
    SleeWord app_word;
    SleeWordDoc *p_doc;
    qDebug()<<Q_FUNC_INFO<<" open a doc ...";
    p_doc = app_word.open_document(qstr_filenamepath);
    if(ui->chb_show_word->isChecked())
    {
        app_word.set_visible(true);
    }

    QString qstr_new;
    SLEE_HDB_REC qh_ap_data = mp_dbms->get_data(LAKDB_APARTMENTS, mqh_lease[FLD_LS_AINDEX]);
    SLEE_HDB_REC qh_t_data = mp_dbms->get_data(LAKDB_TENANTS, mqh_lease[FLD_LS_TINDEX]);
    SLEE_HDB_REC qh_h_data = mp_dbms->get_data(LAKDB_HOUSES, qh_ap_data[FLD_APDB_HSINDEX]);

    qDebug()<<Q_FUNC_INFO<<" fill up ....";

    qstr_new = mqh_lease[FLD_LS_NUM].toString();
    replace(p_doc, "$L-NUM", qstr_new);

    qstr_new.sprintf("%d",mqh_lease[FLD_LS_SDATE].toDate().day());
    replace(p_doc, "$L-DD", qstr_new);

    qstr_new = qstr_m_list.at(mqh_lease[FLD_LS_SDATE].toDate().month()-1);
    replace(p_doc, "$L-MM", qstr_new);

    qstr_new.sprintf("%d",mqh_lease[FLD_LS_SDATE].toDate().year());
    replace(p_doc, "$L-YYYY", qstr_new);

    qstr_new = mp_dbms->get_tenant_fio(mqh_lease[FLD_LS_TINDEX], true);
    replace(p_doc, "$T-FIO", qstr_new);

    QVariantList qvl_dec_indicies = mqh_lease.value(FLD_LS_DECLST).toList();
    QVariantList qvl_dec_numbers = mqh_lease.value(FLD_LS_DNUMLST).toList();
    QVariantList qvl_dec_dates = mqh_lease.value(FLD_LS_DDATESLST).toList();

    for(int i = 0; i<qvl_dec_indicies.size(); i++)
    {
        qstr_new = "^l";
        qstr_new += mp_dbms->get_data(LAKDB_DECMASTERS, qvl_dec_indicies.at(i)).value(FLD_DECDB_NAME).toString();
        qstr_new += RUSTR(" № ");
        qstr_new += qvl_dec_numbers.at(i).toString();
        qstr_new += RUSTR(" от ");
        QDate qd = qvl_dec_dates.at(i).toDate();
        qstr_new += qd.toString("\"dd\" ");
        qstr_new += qstr_m_list.at(qd.month()-1);
        qstr_new += qd.toString(" yyyy");
        qstr_new += RUSTR("г. ");
        if(i < (qvl_dec_indicies.size()-1))
            qstr_new += "$DM-INFO-LIST";

        if(!p_doc->replace("$DM-INFO-LIST", qstr_new)) qDebug()<<"decm list marker not found";
    }

    qstr_new = QString::number(mp_dbms->get_leases_rooms_count(mqh_lease));
    replace(p_doc, "$AP-RNUM", qstr_new);

    qstr_new = qh_ap_data[FLD_APDB_RCOUNT].toString();
    replace(p_doc, "$AP-RCOUNT", qstr_new);

    qstr_new = qh_ap_data[FLD_APDB_TSPC].toString();
    replace(p_doc, "$AP-TSPC", qstr_new);

    qstr_new =  QString::number(mp_dbms->get_apartment_lspace(mqh_lease.value(FLD_LS_AINDEX)));
    replace(p_doc, "$AP-LSPC", qstr_new);

    qstr_new = mp_dbms->get_apartment_addr(mqh_lease[FLD_LS_AINDEX]);
    replace(p_doc, "$AP-ADDR", qstr_new);

    QStringList fac_lst = mp_dbms->get_facilities_list(qh_h_data[FLD_HSDB_FACILITIES].toInt());
    for(int i = 0; i < fac_lst.size(); i++)
    {
        qstr_new = fac_lst.at(i);
        if(i < (fac_lst.size() - 1))
            qstr_new += ", $FACILITIES-LIST";
        else
            qstr_new += ".";

        if(!p_doc->replace("$FACILITIES-LIST", qstr_new)) qDebug()<<"facilities list marker not found";
    }

    SLEE_HDB_REC_LST qh_mfam_lst;
//    SLEE_HDB_REC qh_p_data;

    mp_dbms->get_db(LAKDB_FAMILIES)->findDataEq(FLD_FAM_TINDEX,mqh_lease.value(FLD_LS_TINDEX),&qh_mfam_lst);
    int i = 0;
    foreach(SLEE_HDB_REC qh_data, qh_mfam_lst)
    {
        qstr_new.sprintf("^l%d) ", i+1);
        qstr_new += qh_data[FLD_FAM_FAM].toString();
        qstr_new += " ";
        qstr_new += qh_data[FLD_FAM_NAME].toString();
        qstr_new += " ";
        qstr_new += qh_data[FLD_FAM_PNAME].toString();
        qstr_new += " ^+ ";
        qstr_new += qh_data[FLD_FAM_RELATION].toString();
        qstr_new += " ";
        qstr_new += qh_data[FLD_FAM_DOB].toDate().toString("dd.MM.yyyy");
        qstr_new += RUSTR("г.р.");
        if(i < (qh_mfam_lst.size() - 1))
        {
            qstr_new += "$FAM-MEM-LIST";
        }
        p_doc->replace("$FAM-MEM-LIST", qstr_new);
        i++;
    }
    qstr_new = mqh_lease[FLD_LS_LENDER_HEAD].toString();
    replace(p_doc, "$LENDER-HEAD", qstr_new);

    qstr_new = mqh_lease[FLD_LS_LENDER_HFIO].toString();
    replace(p_doc, "$LENDER-HFIO", qstr_new);


    qstr_new = qh_t_data.value(FLD_TEN_DOB).toDate().toString("dd.MM.yyyy");
    replace(p_doc, "$T-DOB", qstr_new);

    qstr_new = qh_t_data[FLD_TEN_REGADR].toString();
    replace(p_doc, "$T-REG-ADDR", qstr_new);

    qstr_new = qh_t_data[FLD_TEN_PASSNUM].toString();
    replace(p_doc, "$T-PASS-NUM", qstr_new);

    qstr_new = qh_t_data[FLD_TEN_PASSDATE].toDate().toString("dd.MM.yyyy");
    replace(p_doc, "$T-PASS-DATE", qstr_new);

    qstr_new = qh_t_data[FLD_TEN_PASSDEP].toString();
    replace(p_doc, "$T-PASS-SRC", qstr_new);

    p_doc->save();
    if(ui->chb_quit_word->isChecked())
    {
        app_word.quit_word();
    }
 #endif

}

